package com.azt.dao.impl;

import com.azt.dao.JedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 单机redis
 * String 类型存取
 *
 * @author 张栋 2016年6月24日下午2:43:11
 */
@Repository
public class JedisClientSingle implements JedisClient {

	private static Logger logger = LoggerFactory.getLogger(JedisClientSingle.class);

	@Autowired
	private StringRedisTemplate  redisTemplate;

	private static   Boolean closeRedis = false;
	private static Timer delay=null;

	public synchronized void closeRedis() {
		if(delay==null){
			closeRedis=true;
			delay = new Timer();
			delay.schedule(new TimerTask() {
				public void run() {
					delay.cancel();
					delay=null;
					closeRedis=false;
				}
			}, 30*60*1000);
		}
	}
	@Override
	public String get(String key) {
		if(closeRedis){
			return null;
		}


		Object o = null;
		try {
			o = redisTemplate.opsForValue().get(key);
		} catch (Exception e) {
			closeRedis();
			logger.error("redis连接失败",e);
		}
		return o==null?null:o.toString();
	}

	@Override
	public void set(String key, String value) {
		if(closeRedis){
			return ;
		}
		try {
			redisTemplate.opsForValue().set(key,value);
		} catch (Exception e) {
			closeRedis();
			logger.error("redis连接失败",e);
		}
	}

	@Override
	public void del(String key) {
		if(closeRedis){
			return ;
		}
		try {
			redisTemplate.delete(key);
		} catch (Exception e) {
			closeRedis();
			logger.error("redis连接失败",e);
		}
	}

	@Override
	public String hget(String hkey, String key) {
		if(closeRedis){
			return null;
		}

		Object o = null;
		try {
			o = redisTemplate.opsForHash().get(hkey, key);
		} catch (Exception e) {
			closeRedis();
			logger.error("redis连接失败",e);
		}
		return o==null?null:o.toString();
	}



	@Override
	public void hset(String hkey, String key, String value) {
		if(closeRedis){
			return ;
		}
		try {
			redisTemplate.opsForHash().put(hkey,key,value);
		} catch (Exception e) {
			closeRedis();
			logger.error("redis连接失败",e);
		}
	}



	@Override
	public void hdel(String hkey, String key) {
		if(closeRedis){
			return ;
		}
		try {
			redisTemplate.opsForHash().delete(hkey,key);
		} catch (Exception e) {
			closeRedis();
			logger.error("redis连接失败",e);
		}
	}

}
